# -*- coding: utf-8 -*-
import webapp2
import exceptions

from storage import Piece
from webapp2 import uri_for
from storage import Product


class ViewLists(webapp2.RequestHandler):
    
    def get(self, *args, **kwargs):
        self.response.write('<html><body>Список: <ul>')
        piece_query = Piece.query().order(Piece.date)
        unit_query = Product.query()
        for item in unit_query:
            schet = 0
            sz = 0
            for item2 in piece_query:
                if item2.is_bought == False:
                    if item2.what == item.what:
                        schet += item2.quantity
                        sz += 1
            if schet != 0:
                self.response.write('%s' %(item.what))
                if sz > 1:
                    self.response.write(': %d штук(и)' %(schet))
                self.response.write('<ul>')
                for item2 in piece_query:
                    if item2.is_bought == False:
                        if item2.what == item.what:
                            self.response.write('<li>%s %d</li>' % (item2.who, item2.quantity))
                self.response.write('</ul>')
        self.response.write('</ul>')
        self.response.write("""
            <form action="%s" method="post">
                <label for="list">Заказать: Кто, что, сколько:</label>
                <input id="man" type="text" name="man">
                <input id="product" type="text" name="product">
                <input id="size" type="text" name="size">
                <input type="submit" name="Add" value = "Добавить">
            </form>
            <form action="%s" method="post">
                <label for="list1">Заказ выполнен: Что, сколько:</label>
                <input id=product1" type="text" name="product1">
                <input id="size1" type="text" name="size1">
                <input type="submit" name="Edit" value = "Внести изменения">
            </form>
            <form action="%s" method="post"><input type="submit" value="Очистить лист покупок"></form>
            </body>
            </html>""" % (uri_for('add'), uri_for('edit'), uri_for('clear')))
        
        
class AddList(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(AddList, self).__init__(*args, **kwargs)
    def post(self, *args, **kwargs):
        try:
            Name = self.request.get('man')
            if Name == "":
                self.redirect(uri_for('show'))
                return
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return
        try:
            View = self.request.get('product')
            if View == "":
                self.redirect(uri_for('show'))
                return            
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return
        try:
            Number = int(self.request.get('size'))
            if Number <= 0:
                self.redirect(uri_for('show'))
                return            
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return
        piece_query = Piece.query().order(Piece.date)
        unit_query = Product.query()
        piece = Piece(who = Name, what = View, quantity = Number)
        unit = Product(what = View)
        piece.put()
        is_not_in_the_list= True #если ли этот продукт в списке покупок
        for item in unit_query:
            if item.what == unit.what:
                is_not_in_the_list = False
        if is_not_in_the_list:
            unit.put()       
        self.redirect(uri_for('show'))
        
        
class EditList(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(EditList, self).__init__(*args, **kwargs) 
    def post(self, *args, **kwargs):
        try:
            View = self.request.get('product1')
            if View == "":
                self.redirect(uri_for('show'))
                return
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return
        try:
            Number = int(self.request.get('size1'))
            if Number <= 0:
                self.redirect(uri_for('show'))
                return
        except exceptions.ValueError:
            self.redirect(uri_for('show'))
            return       
        piece_query = Piece.query().order(Piece.date)
        piece = Piece(what = View, quantity = Number)
        is_not_in_the_list=True
        for item in piece_query:
            if item.what == piece.what:
                is_not_in_the_list=False
        if is_not_in_the_list:
            self.redirect(uri_for('show'))
            return
        for item in piece_query:
            if item.what == piece.what:
                if item.quantity > piece.quantity:
                    item.quantity -= piece.quantity
                    piece.quantity = 0
                    item.put()
                    self.redirect(uri_for('show'))
                elif item.quantity == piece.quantity:
                    item.is_bought = True
                    piece.quantity = 0
                    item.quantity = 0
                    item.put()
                    self.redirect(uri_for('show'))
                else:
                    piece.quantity -= item.quantity
                    item.quantity = 0
                    item.is_bought = True
                    item.put()
                    self.redirect(uri_for('show'))


class Clear(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(Clear, self).__init__(*args, **kwargs) 
    def post(self, *args, **kwargs):
        for item_key in Piece.query().iter(keys_only=True):
            item_key.delete()
        for th_key in Product.query().iter(keys_only=True):
            th_key.delete()
        self.redirect(uri_for('show'))